package com.xy.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

public class ScatteringAndGatheringTest {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        serverSocketChannel.socket().bind(inetSocketAddress);
        //创建buffer数组
        ByteBuffer[] buffers = new ByteBuffer[2];
        buffers[0] = ByteBuffer.allocate(5);
        buffers[1] = ByteBuffer.allocate(3);

        //socket
        SocketChannel socketChannel = serverSocketChannel.accept();
        int msgLength = 8;
        while (true) {
            int byteRead = 0;
            while (byteRead < msgLength) {
                long l = socketChannel.read(buffers);
                byteRead += l;
                System.out.println("byteRead=" + byteRead);
                Arrays.asList(buffers).stream().map( buffer ->
                    "postion:" + buffer.position() + ",limit" + buffer.limit()
                ).forEach(System.out::println);
            }
            Arrays.asList(buffers).stream().forEach( buffer -> buffer.flip());
            int byteWite = 0;
            while (byteWite < msgLength) {
                long l = socketChannel.write(buffers);
                byteWite += l;
            }
            Arrays.asList(buffers).stream().map( buffer -> buffer.clear());
            System.out.println("byteWrite=" + byteWite);
        }
    }
}
